package com.moddevapp.phoneutil;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.CallLog.Calls;
import android.util.Log;

public class MissCallService extends Service {
	private static int lastCount = 0;
	
	//get missed call count
	public int getMissedCallCount(Context context) {
        Cursor cursor = getApplicationContext().getContentResolver().query(
	            Calls.CONTENT_URI, 
	            null, 
	            Calls.TYPE +  " = ? AND " + Calls.NEW + " = ?", 
	            new String[] { Integer.toString(Calls.MISSED_TYPE), "1" }, 
	            Calls.DATE + " DESC ");

	    //this is the number of missed calls
	    //for your case you may need to track this number
	    //so that you can figure out when it changes
	    return cursor.getCount(); 		
	}
	
	public int checkCurrentMissedCall() {
        Cursor cursor = getApplicationContext().getContentResolver().query(
	            Calls.CONTENT_URI, 
	            null, 
	            Calls.TYPE +  " = ? AND " + Calls.NEW + " = ?", 
	            new String[] { Integer.toString(Calls.MISSED_TYPE), "1" }, 
	            Calls.DATE + " DESC ");
        
        int saveCurCount = cursor.getCount();
        Log.d("PhoneUtil", "Current Missed " + saveCurCount + " last missed " + lastCount);
        //show all missed count between last missed and current missed
        if(saveCurCount > lastCount) {
        	if(cursor.moveToLast()) {
	        	Log.d("PhoneUtil", "Number: " + cursor.getString(6));
	        	Log.d("PhoneUtil", "Data: " + cursor.getString(8));
        	}
        }
        //update last missed call count
        lastCount = saveCurCount;

        return 0;
	}
	
	class MissedCallsContentObserver extends ContentObserver
	{
	    public MissedCallsContentObserver()
	    {
	        super(null);
	    }

	    @Override
	    public void onChange(boolean selfChange)
	    {
	    	checkCurrentMissedCall();   
	    }
	}	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		lastCount = getMissedCallCount(getApplicationContext());
		Log.d("PhoneUtil", "Start phone util service with " + lastCount + " missed call");
		
        MissedCallsContentObserver mcco = new MissedCallsContentObserver();
        getApplicationContext().getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, mcco);
		
	    // We want this service to continue running until it is explicitly
	    // stopped, so return sticky.
	    return START_STICKY;
	}
}